package com.cxs.shopstore.utils;

import com.cxs.shopstore.config.ImgConf;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/*
 * @Author:cxs
 * @Date:2021/5/2  20:57
 * @Version 1.0
 * */
@Slf4j
@Component
@SuppressWarnings("all")
public class DataCatch {

    @Autowired
    private ImgConf imgConf;

    private final PoolingHttpClientConnectionManager pool;

    private CloseableHttpClient httpClient;

    private CloseableHttpResponse respose;

    public DataCatch() {
        //初始化连接池
        this.pool = new PoolingHttpClientConnectionManager();
        this.pool.setMaxTotal(100);
        this.pool.setDefaultMaxPerRoute(10);
        log.info("初始化httpClient连接池完毕");
    }
    public String catchDataGet(String keyword,int pageno) throws Exception {
        String url = "https://search.jd.com/Search?s=56&click=0&keyword="+keyword+"&page="+pageno;
        httpClient = HttpClients.custom().setConnectionManager(this.pool).build();
        HttpGet getRequest = new HttpGet(url);
        //设置请求头,模仿环境，否则会提示登录
        getRequest.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0");
        getRequest.setConfig(this.getConfig());
        try {
            respose = httpClient.execute(getRequest);
            if(respose.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = respose.getEntity();
                if(entity != null){
                    log.info("数据抓取完成，开始同步数据");
                    return EntityUtils.toString(entity);
                }else{
                    throw new Exception("没有抓到数据");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("出错了，请重新尝试");
            return "";
        }
        return "";
    }

    /**
     * 设置请求参数
     * @return
     */
    private RequestConfig getConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(1000)
                .setSocketTimeout(10*1000).build();
    }

    public String saveImgGet(String imgUrl){
        System.out.println(imgUrl);
        FileOutputStream out;
        httpClient = HttpClients.custom().setConnectionManager(this.pool).build();
        HttpGet getRequest = new HttpGet(imgUrl);
        RequestConfig config = this.getConfig();
        //设置请求头,模仿环境，否则会提示登录
        getRequest.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0");
        getRequest.setConfig(config);
        try {
            respose = httpClient.execute(getRequest);
            if(respose.getStatusLine().getStatusCode() == 200){
                if(respose.getEntity() != null){
                    //获得图片的后缀
                    String posturl = imgUrl.substring(imgUrl.lastIndexOf("."));
                    //生成图片名
                    String imgName = UUID.randomUUID().toString().replaceAll("-","") + posturl;
                    File file = new File(imgConf.getBasePath() + imgName);
                    out = new FileOutputStream(file);
                    respose.getEntity().writeTo(out);
                    log.info("image download success");
                    return imgConf.getBasePath() + imgName;
                }else{
                    log.warn("response.getEntity() is null");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("出错了，请重新尝试");
            return "";
        }
        return "";
    }
}
